import os
import socket
import struct

def send_file(file_path, host, port):
    filename = os.path.basename(file_path)
    filesize = os.path.getsize(file_path)
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client_socket.connect((host, port))

    # 发送固定长度头信息
    header = struct.pack('128sl', filename.encode(), filesize)
    client_socket.sendall(header)

    # 分块发送文件
    with open(file_path, 'rb') as f:
        while True:
            chunk = f.read(4096)
            if not chunk:
                break
            client_socket.sendall(chunk)
            print(f'已发送 {len(chunk)} 字节')
            print(f'进度: {f.tell() / filesize:.2%}')
    client_socket.close()
    print('发送完成')

ip = socket.gethostname()


# send_file('1.jpg', ip, 8888)


while True:

    file_path = input('请输入文件:')
    # 广州
    # ip = '8.138.202.130'

    # 美国
    # ip = '47.88.63.219'
    send_file(file_path, ip, 8888)



















































































